// packageX/business_district_management/member_management/member_management.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    members: [],
    memberCategory: [],
    districtId: '',
    searchKeyword: '',
    activeFilter: 'all',
    categoryId: '',
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    showTitlePopup: false,
    showExtensionPopup: false,
    currentMemberId: '',
    currentMemberName: '',
    selectedTitleId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options && options.id) {
      this.setData({
        districtId: options.id
      });
      this.getMemberCategory();
      this.getMemberList();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      hasMore: true,
      members: []
    });
    this.getMemberList();
    this.getMemberCategory();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageNum: this.data.pageNum + 1
      });
      this.getMemberList();
    }
  },

  /**
   * 获取会员分类（头衔）
   */
  getMemberCategory() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-member.get-categories");
    app._getNetWork({
      url: urlStr,
      data: {
        circle_id: this.data.districtId
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            memberCategory: res.data.list || []
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('获取会员分类失败:', res);
      }
    });
  },

  /**
   * 格式化日期函数
   */
  formatDate(date) {
    if (!date) return '';
    // 处理时间戳格式
    if (typeof date === 'number') {
      date = new Date(date);
    } else if (typeof date === 'string' && !isNaN(date)) {
      date = new Date(Number(date));
    } else if (typeof date === 'string') {
      // 尝试解析日期字符串
      const parsedDate = new Date(date);
      if (!isNaN(parsedDate.getTime())) {
        date = parsedDate;
      } else {
        return date; // 如果无法解析，返回原始字符串
      }
    }
    
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return '';
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  /**
   * 获取会员列表
   */
  getMemberList() {
    if (this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    let that = this;
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-member.get-member-list");
    app._getNetWork({
      url: urlStr,
      data: {
        circle_id: this.data.districtId,
        page: this.data.pageNum,
        pageSize: this.data.pageSize,
        keyword: this.data.searchKeyword,
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let newMembers = res.data.list || [];
          
          // 处理会员数据 - 格式化到期时间
          newMembers = newMembers.map(member => ({
            ...member,
            expire_time: that.formatDate(member.expire_time || member.expireTime || '')
          }));
          
          const allMembers = that.data.pageNum === 1 ? newMembers : [...that.data.members, ...newMembers];
          
          that.setData({
            members: allMembers,
            hasMore: newMembers.length === that.data.pageSize
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('获取会员列表失败:', res);
        wx.showToast({
          icon: 'none',
          title: '获取数据失败',
          duration: 1500
        });
      },
      complete: function() {
        that.setData({
          loading: false
        });
      }
    });
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.setData({
      pageNum: 1,
      hasMore: true,
      members: []
    });
    this.getMemberList();
  },

  /**
   * 筛选点击
   */
  onFilterClick(e) {
    const type = e.currentTarget.dataset.type;
    if(type === 'all') {
      this.setData({
        categoryId: '',
        activeFilter: 'all'
      });
    } else {
      this.setData({
        categoryId: type,
        activeFilter: type
      });
    }
    this.setData({
      pageNum: 1,
      hasMore: true,
      members: []
    });
    this.getMemberList();
  },

  /**
   * 更改会员头衔
   */
  onChangeTitleTap(e) {
    const { id, name } = e.currentTarget.dataset;
    const currentTitleId = this.data.members.find(member => member.id === id)?.category_id || '';
    
    this.setData({
      currentMemberId: id,
      currentMemberName: name,
      selectedTitleId: currentTitleId,
      showTitlePopup: true
    });
  },

  /**
   * 选择头衔
   */
  onSelectTitle(e) {
    console.log(e)
    this.setData({
      selectedTitleId: e.detail.value.id
    });
  },

  onCancel() {
    this.setData({
      "showTitlePopup": false
    });
  },

  /**
   * 确认更改头衔
   */
  onConfirmTitle() {
    if (!this.data.selectedTitleId) {
      wx.showToast({
        title: '请选择头衔',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '处理中' });
    
    let that = this;
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-member.edit-member");
    app._getNetWork({
      url: urlStr,
      data: {
        id: this.data.currentMemberId,
        category_id: this.data.selectedTitleId
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '更改成功',
            icon: 'success'
          });
          // 重新获取会员列表
          that.setData({
            pageNum: 1,
            hasMore: true,
            members: []
          });
          that.getMemberList();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('更改头衔失败:', res);
        wx.showToast({
          icon: 'none',
          title: '操作失败，请重试',
          duration: 1500
        });
      },
      complete: function() {
        wx.hideLoading();
        that.setData({
          showTitlePopup: false
        });
      }
    });
  },

  /**
   * 关闭头衔弹窗
   */
  onCloseTitlePopup() {
    this.setData({
      showTitlePopup: false
    });
  },

  /**
   * 会员延期
   */
  onExtensionTap(e) {
    const { id, name } = e.currentTarget.dataset;
    this.setData({
      currentMemberId: id,
      currentMemberName: name,
      showExtensionPopup: true
    });
  },

  /**
   * 确认延期
   */
  onConfirmExtension() {
    wx.showLoading({ title: '处理中' });
    
    let that = this;
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-member.edit-member");
    app._getNetWork({
      url: urlStr,
      data: {
        id: this.data.currentMemberId,
        extension: 1
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '延期成功',
            icon: 'success'
          });
          // 重新获取会员列表
          that.setData({
            pageNum: 1,
            hasMore: true,
            members: []
          });
          that.getMemberList();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('会员延期失败:', res);
        wx.showToast({
          icon: 'none',
          title: '操作失败，请重试',
          duration: 1500
        });
      },
      complete: function() {
        wx.hideLoading();
        that.setData({
          showExtensionPopup: false
        });
      }
    });
  },

  /**
   * 关闭延期弹窗
   */
  onCloseExtensionPopup() {
    this.setData({
      showExtensionPopup: false
    });
  }
});